package persistence;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import utilities.Logger;

public class DatabaseManager {
	
	private static Logger log = Logger.getLogger( DatabaseManager.class );
	private static DatabaseManager dbm;
	private Connection c;
	
	/**
	 * Creates a new instance of DatabaseManager
	 */
	protected DatabaseManager() { 
		dbm = this;
	}
	
	/**
	 * Creates a new / returns existing instance of DatabaseManager
	 * @return
	 */
	public static DatabaseManager getInstance() {
		if (dbm == null)
			return new DatabaseManager();
		return dbm;
	}

	/**
	 * Opens a connection to HSQLDB-Server
	 * @param host Adress
	 * @param user User
	 * @param pw Password
	 * @throws SQLException In case of connection-problems.
	 * @throws ClassNotFoundException In case of HSQLDB/JDBC error. (Not installed?)
	 */
	public void openConnection(String host, String user, String pw) throws SQLException, ClassNotFoundException {
		log.i("Opening connection ... ");
		Class.forName("org.hsqldb.jdbcDriver"); 
		c = DriverManager.getConnection(host,user,pw);
		log.i("Connection established.");
	}
	
	/**
	 * @return Returns existing connection
	 */
	public Connection getConnection() {
			return c;
	}
	
	/**
	 * Closes connection
	 * @throws SQLException In case of (miscellaneous) SQL-Error
	 */
	public void closeConnection() throws SQLException {
			log.i("Closing connection ... ");
			c.close();
			c = null;
			log.i("Connection closed.");
	}
}
